package net.wicp.tams.duckula.server;

import java.io.File;
import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import com.spotify.docker.client.DockerClient.ListImagesParam;
import com.spotify.docker.client.messages.Image;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.others.docker.DockerUtilSpotify;

@Configuration
@Slf4j
public class ConfigInit implements EnvironmentAware {

	@Override
	public void setEnvironment(Environment environment) {
		String propPath = IOUtil.mergeFolderAndFilePath(System.getenv("DUCKULA_HOME"),
				"/conf/duckula-server.properties");
		Properties props = IOUtil.fileToProperties(new File(propPath));
		Conf.overProp(props);
		log.info("prop num:{}", props.size());

		String enableDocker = Conf.get("duckula.docker.enable");
		if (StringUtil.isTrueStr(enableDocker)) {
			try {
				String duckulaVersion = Conf.get("duckula.docker.version");
				String imageid = Conf.get("duckula.docker.imageid");
				List<Image> images = DockerUtilSpotify.getInst().getDocker()
						.listImages(ListImagesParam.withLabel("duckulaVersion", duckulaVersion));
				if (CollectionUtils.isEmpty(images)) {// 自动创建dockerimages
					final String returnedImageId = DockerUtilSpotify.getInst().getDocker()
							.build(Paths.get(new File(System.getenv("DUCKULA_HOME")).toURI()), imageid);
					log.info("生成images:{}", returnedImageId);
				}
			} catch (Exception e) {
				log.error("试图创建image出错,请手工创建相关的image", e);
			}
		}
	}
}
